// src/store/userStore.js
import { create } from 'zustand';
import axios from '../api/axios';
import { endpoints } from '../api/endpoints';

export const useUserStore = create((set, get) => ({
  user: null,
  loading: false,
  error: null,
  
  
  // Update user profile
  updateUserProfile: async (userData) => {
    set({ loading: true, error: null });
    try {
      // Simulated API response for profile update
      // In real implementation, this would be:
      // const response = await axios.put(endpoints.profile, userData);
      
      // For mock implementation
      return new Promise((resolve) => {
        setTimeout(() => {
          const updatedUser = { ...get().user, ...userData };
          set({ user: updatedUser, loading: false });
          resolve({ data: updatedUser });
        }, 600);
      });
    } catch (error) {
      set({ 
        error: error.response?.data?.message || "Failed to update profile", 
        loading: false 
      });
      throw error;
    }
  },

  // Redeem membership
  redeemMembership: async (exchangeCode) => {
    set({ loading: true, error: null });
    try {
      const response = await axios.post(endpoints.redeemMembership, {
        exchan_sn: exchangeCode
      });
      
      if (response.data.success) {
        set({ loading: false });
        return { success: true, message: response.data.msg };
      } else {
        set({ 
          error: response.data.msg || "兑换失败", 
          loading: false 
        });
        return { success: false, message: response.data.msg };
      }
    } catch (error) {
      const errorMessage = error.response?.data?.msg || "兑换码无效";
      set({ 
        error: errorMessage, 
        loading: false 
      });
      throw new Error(errorMessage);
    }
  },
  
  // Clear user data (for logout)
  clearUser: () => set({ user: null }),
  
  // Clear errors
  clearErrors: () => set({ error: null })
}));